import 'package:flutter/material.dart';
import '../services/alger_api_service.dart';
import 'alger_playlist_detail_screen.dart';

class AlgerPlaylistScreen extends StatefulWidget {
  const AlgerPlaylistScreen({super.key});

  @override
  State<AlgerPlaylistScreen> createState() => _AlgerPlaylistScreenState();
}

class _AlgerPlaylistScreenState extends State<AlgerPlaylistScreen> {
  final AlgerApiService _api = AlgerApiService();
  List<AlgerCategory> _categories = [];
  String? _selectedCat;
  List<AlgerPlaylist> _playlists = [];
  bool _loadingCats = true;
  bool _loadingPlaylists = false;
  final ScrollController _catController = ScrollController();
  // 分页状态
  int _limit = 22;
  int _offset = 0;
  bool _hasMore = true;
  bool _loadingMore = false;

  @override
  void initState() {
    super.initState();
    _loadCategories();
  }

  Future<void> _loadCategories() async {
    setState(() => _loadingCats = true);
    try {
      final cats = await _api.fetchCategories();
      setState(() {
        //内置一个分类 推荐
        cats.insert(0, AlgerCategory('推荐'));
        _categories = cats;
        _selectedCat = cats.isNotEmpty ? cats.first.name : null;
      });
      if (_selectedCat != null) {
        await _loadPlaylists(_selectedCat!);
      }
    } catch (e) {
      debugPrint('加载分类失败: $e');
    } finally {
      if (mounted) setState(() => _loadingCats = false);
    }
  }

  Future<void> _loadPlaylists(String cat) async {
    setState(() {
      _loadingPlaylists = true;
      _offset = 0;
      _hasMore = true;
      _playlists = [];
    });
    try {
      final list = await _api.fetchTopPlaylists(cat: cat, limit: _limit, offset: _offset);
      setState(() {
        _playlists = list;
        _hasMore = list.length >= _limit;
      });
    } catch (e) {
      debugPrint('加载歌单失败: $e');
    } finally {
      if (mounted) setState(() => _loadingPlaylists = false);
    }
  }

  Future<void> _loadMore() async {
    if (_loadingMore || !_hasMore || _selectedCat == null) return;
    setState(() => _loadingMore = true);
    try {
      final nextOffset = _offset + _limit;
      final list = await _api.fetchTopPlaylists(cat: _selectedCat!, limit: _limit, offset: nextOffset);
      setState(() {
        _offset = nextOffset;
        _playlists.addAll(list);
        if (list.length < _limit) _hasMore = false;
      });
    } catch (e) {
      debugPrint('加载更多失败: $e');
    } finally {
      if (mounted) setState(() => _loadingMore = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isWide = MediaQuery.of(context).size.width > 900;
    final crossAxisCount = isWide ? 5 : 2;
    final spacing = 12.0;
    // 增加格子高度以避免文字溢出
    final childAspectRatio = isWide ? 0.70 : 0.66;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 8),
        _buildCategoryBar(),
        const SizedBox(height: 8),
        _loadingPlaylists
            ? const Center(child: CircularProgressIndicator())
            : Column(
                children: [
                  GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: crossAxisCount,
                  mainAxisSpacing: spacing,
                  crossAxisSpacing: spacing,
                  // 图片方形 + 下方两行标题，提高单元格高度
                  childAspectRatio: childAspectRatio,
                ),
                itemCount: _playlists.length,
                itemBuilder: (context, index) {
                  final p = _playlists[index];
                  return GestureDetector(
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (_) => AlgerPlaylistDetailScreen(
                            playlistId: p.id,
                            playlistName: p.name,
                            coverImgUrl: p.coverImgUrl,
                          ),
                        ),
                      );
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(color: Colors.grey[300]!),
                        color: Colors.white,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 方形封面图
                          ClipRRect(
                            borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(12),
                              topRight: Radius.circular(12),
                            ),
                            child: AspectRatio(
                              aspectRatio: 1,
                              child: Stack(
                                children: [
                                  Positioned.fill(
                                    child: p.coverImgUrl.isNotEmpty
                                        ? Image.network(p.coverImgUrl, fit: BoxFit.cover)
                                        : Container(color: Colors.grey[200]),
                                  ),
                                  if (p.playCount > 0)
                                    Positioned(
                                      top: 6,
                                      right: 6,
                                      child: _buildPlayCountBadge(p.playCount),
                                    ),
                                ],
                              ),
                            ),
                          ),
                          // 独立文字行（两行省略）
                          Padding(
                            padding: const EdgeInsets.fromLTRB(8, 8, 8, 10),
                            child: Text(
                              p.name,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              softWrap: true,
                              style: const TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
                  const SizedBox(height: 8),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 12),
                    child: Center(
                      child: _loadingMore
                          ? const SizedBox(height: 32, width: 32, child: CircularProgressIndicator())
                          : _hasMore
                              ? FilledButton.icon(
                                  onPressed: _loadMore,
                                  icon: const Icon(Icons.expand_more),
                                  label: const Text('加载更多'),
                                )
                              : Text(
                                  '没有更多了',
                                  style: TextStyle(color: Colors.grey[600]),
                                ),
                    ),
                  ),
                ],
              ),
      ],
    );
  }

  // 播放量格式化：12345 -> 1.2万， 123456789 -> 1.2亿
  String _formatPlayCount(int count) {
    if (count >= 100000000) {
      final v = count / 100000000;
      return v >= 10 ? v.toStringAsFixed(0) + '亿' : v.toStringAsFixed(1) + '亿';
    }
    if (count >= 10000) {
      final v = count / 10000;
      return v >= 10 ? v.toStringAsFixed(0) + '万' : v.toStringAsFixed(1) + '万';
    }
    return count.toString();
  }

  // 右上角播放量标识
  Widget _buildPlayCountBadge(int count) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.55),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.play_arrow, size: 14, color: Colors.white),
          const SizedBox(width: 3),
          Text(
            _formatPlayCount(count),
            style: const TextStyle(color: Colors.white, fontSize: 12),
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      height: 40,
      child: _loadingCats
          ? const Center(child: CircularProgressIndicator())
          : Scrollbar(
              controller: _catController,
              thumbVisibility: true,
              interactive: true,
              child: ListView.separated(
                controller: _catController,
                scrollDirection: Axis.horizontal,
                itemCount: _categories.length,
                separatorBuilder: (_, __) => const SizedBox(width: 8),
                itemBuilder: (context, index) {
                  final c = _categories[index];
                  final selected = c.name == _selectedCat;
                  return GestureDetector(
                    onTap: () {
                      setState(() => _selectedCat = c.name);
                      _loadPlaylists(c.name);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: selected ? Colors.blue.withOpacity(0.15) : Colors.white,
                        borderRadius: BorderRadius.circular(18),
                        border: Border.all(color: selected ? Colors.blue : Colors.grey[300]!),
                      ),
                      child: Text(
                        c.name,
                        style: TextStyle(
                          fontSize: 12,
                          color: selected ? Colors.blue[800] : Colors.black87,
                          fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
    );
  }
}
